package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.MarketFootprint;
import com.cskaoyan.market.db.domain.MarketFootprintExample;
import com.cskaoyan.market.db.domain.MarketGoods;
import com.cskaoyan.market.db.domain.MarketGoodsExample;
import com.cskaoyan.market.db.mapper.MarketFootprintMapper;
import com.cskaoyan.market.db.mapper.MarketGoodsMapper;
import com.cskaoyan.market.util.AdminResponseCode;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MarketFootprintServiceImpl implements MarketFootprintService {

    @Autowired
    MarketFootprintMapper footprintMapper;

    @Autowired
    MarketGoodsMapper goodsMapper;

    /**
     * 1-查询footprint表找到goodsId
     * 2-通过goodsid找goods表
     * 3-返回goods对象组成的List
     *
     * @param page
     * @param limit
     * @return
     */
    @Override
    public List<MarketGoods> list(Integer id, Integer page, Integer limit) {
        if (id == null) {
            return new ArrayList<MarketGoods>();
        }
        PageHelper.startPage(page, limit);
        List<MarketGoods> result = new ArrayList<>();
        // 生成一个比较器, 根据MarketFootprint的更新时间进行排序
        Comparator comparator = Comparator.comparing(MarketFootprint::getUpdateTime);

        // 把footprint数据都拿出来再说
        MarketFootprintExample footprintExample = new MarketFootprintExample();
        footprintExample.or().andDeletedEqualTo(false).andUserIdEqualTo(id);
        List<MarketFootprint> footprintList = footprintMapper.selectByExample(footprintExample);

        // 利用流对List进行排序, 返回的collect就是排序好的数据
        List<MarketFootprint> collect =
                (List<MarketFootprint>) footprintList.
                        stream().
                        sorted(comparator.reversed()).
                        collect(Collectors.toList());


        for (MarketFootprint footprint : collect) {
            Integer goodsId = footprint.getGoodsId();
            MarketGoodsExample goodsExample = new MarketGoodsExample();
            goodsExample.or().andIdEqualTo(goodsId);
            MarketGoods goods = goodsMapper.selectOneByExample(goodsExample);
            goods.setAddTime(footprint.getAddTime());
            goods.setUpdateTime(footprint.getUpdateTime());
            result.add(goods);
        }
        return result;
    }


    /**
     * 删除id
     *
     * @param id 指的足迹表里是商品的goodsId
     * @return
     */
    @Override
    public int delete(Integer id) {
        try {
            MarketFootprintExample marketFootprintExample = new MarketFootprintExample();
            marketFootprintExample.or().andGoodsIdEqualTo(id);
            footprintMapper.deleteByExample(marketFootprintExample);
            return 200;
        } catch (Exception e) {
            return 666;
        }

    }
}
